package club.xyes.zkh.ecommerce.security.handler;

import club.xyes.zkh.ecommerce.commons.context.ApplicationConstants;
import club.xyes.zkh.ecommerce.commons.vo.GeneralResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 2019/4/15 23:12 Create by 郭文梁（郭文梁）
 * LoginFailHandler
 * 登录失败处理器
 *
 * @author 郭文梁
 */
@Component
public class LoginFailHandler implements AuthenticationFailureHandler {
    private final ObjectMapper objectMapper;

    @Autowired
    public LoginFailHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        GeneralResult<Object> res = GeneralResult.permissionDenied(exception.getMessage());
        String respJson = objectMapper.writeValueAsString(res);
        response.setCharacterEncoding(ApplicationConstants.DEFAULT_CHARSET);
        response.setContentType(ApplicationConstants.Http.CONTENT_TYPE_JSON_UTF8);
        response.getWriter().write(respJson);
    }
}
